import asyncio
import os
import signal
import time

from gmqtt import Client as MQTTClient

# gmqtt also compatibility with uvloop
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())


STOP = asyncio.Event()


def on_connect(client, flags, rc, properties):
    print("Connected")
    # 订阅主题
    # client.subscribe("TEST/#", qos=0)


def on_message(client, topic, payload, qos, properties):
    print(f"recv {topic}: {payload}")


def on_disconnect(client, packet, exc=None):
    print("Disconnected")


def on_subscribe(client, mid, qos, properties):
    print("SUBSCRIBED")


def ask_exit(*args):
    STOP.set()


async def main(broker_host):
    client = MQTTClient("client-id2")

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe
    await client.connect(broker_host)

    count: int = 0
    while count < 100:
        client.publish("TEST/topic", f"hello gmqtt {count}")
        count += 1
        await asyncio.sleep(1)

    await STOP.wait()
    await client.disconnect()


if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    host = "127.0.0.1"

    loop.add_signal_handler(signal.SIGINT, ask_exit)
    loop.add_signal_handler(signal.SIGTERM, ask_exit)

    loop.run_until_complete(main(host))
